import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/module/match/list/lq_end_logic.dart';
import 'package:ball_lion/module/match/list/lq_match_filter_logic.dart';
import 'package:ball_lion/module/match/list/lq_view_logic.dart';
import 'package:ball_lion/module/match/list/match_page_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/loading/loading_match_list.dart';
import 'package:ball_lion/module/match/basketball/lq_match_cell.dart';
import 'package:ball_lion/module/match/match_filter_float_widget.dart';
import 'package:ball_lion/widgets/bottom_picker_widget.dart';
import 'package:ball_lion/widgets/date_tab_bar.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/widgets/ads_label.dart';

class LqEndView extends StatefulWidget {
  const LqEndView({super.key});

  @override
  State<LqEndView> createState() => _LqEndViewState();
}

class _LqEndViewState extends State<LqEndView> with TickerProviderStateMixin {
  final logic = Get.put(LqEndLogic());
  late TabController _tabController;

  final days = List.generate(
          7, (index) => DateTime.now().subtract(Duration(days: index)))
      .reversed
      .toList();
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
        length: days.length, vsync: this, initialIndex: days.length - 1);
    _tabController.addListener(() {
      logic.changeIndex(_tabController.index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqEndLogic>(builder: (_) {
      return Stack(
        children: [
          Column(
            children: [
              Container(
                height: 53,
              ),
              Expanded(
                child: ExtendedTabBarView(
                  controller: _tabController,
                  children: days
                      .map((e) => BasketEndListView(e, days.indexOf(e)))
                      .toList(),
                ),
              ),
            ],
          ),
          Positioned(top: 0, left: 0, right: 0, child: dateWidget()),
          Positioned(
              bottom: 40,
              child: MatchFilterFloatWidget(
                1,
                false,
                logic.quickFilter,
                onTap: (index) {
                  logic.selectMatchType(index);
                },
              )),
          Styles.matchListBottomBar(
              logic.hideMatchNum != 0 && !logic.isBottomHide,
              logic.hideMatchNum, onClose: () {
            Utils.onEvent('bspd_sxfc_gb');
            logic.onCloseBottomBar();
          }, onDefault: () {
            Utils.onEvent('bspd_sxfc_hf');
            logic.selectMatchType(QuickFilter.all);
            // update();
          })
        ],
      );
    });
  }

  dateWidget() {
    return Container(
      height: 53,
      decoration: BoxDecoration(color: Colours.white, boxShadow: [
        BoxShadow(
          color: Color(0x0C0F499F),
          offset: Offset(0, 2),
          blurRadius: 12,
        ),
      ]),
      child: Row(
        children: [
          Expanded(
            child: DateTabBar(
              onTap: (value) {
                Utils.onEvent('bspd_rql_rl');
                logic.changeIndex(value);
              },
              dateList: days,
              controller: _tabController,
              labelPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 5),
              indicatorSize: TabBarIndicatorSize.label,
              labelStyle: const TextStyle(height: 2),
            ),
          ),
          Container(
            width: 1,
            height: 30,
            color: Colours.grey7FC2C2C2,
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Utils.onEvent('bspd_rql_sx');
              _showDatePicker();
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              child: Image.asset(
                Utils.getImgPath('calendar.png'),
                fit: BoxFit.fill,
                width: 22,
                height: 22,
              ),
            ),
          )
        ],
      ),
    );
  }

  void _showDatePicker() async {
    // var locale = Localizations.localeOf(context);
    List<String> title = days
        .map((e) =>
            '${DateFormat.MMMd('zh_cn').format(e)} ${DateFormat.E('zh_cn').format(e)}')
        .toList();
    final selectIndex = await Get.bottomSheet(BottomPickerWidget(
      title,
      title: '比赛日期',
      initialIndex: logic.index,
    ));
    _tabController.animateTo(selectIndex);
  }
}

class BasketEndListView extends StatefulWidget {
  final DateTime date;
  final int pageIndex;
  const BasketEndListView(this.date, this.pageIndex, {super.key});

  @override
  State<BasketEndListView> createState() => _BasketEndListViewState();
}

class _BasketEndListViewState extends State<BasketEndListView> {
  late LqViewLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(
        LqViewLogic(LqMatchType.end, Constant.matchFilterTagResult,
            date: widget.date),
        tag: '${Constant.matchFilterTagResult}${widget.pageIndex}',
        permanent: true);
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   PrimaryScrollController.of(context).addListener(didScroll);
  //   log('didChangeDependencies');
  // }

  // @override
  // void deactivate() {
  //   PrimaryScrollController.of(context).removeListener(didScroll);
  //   super.deactivate();
  //   log('deactivate');
  // }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqViewLogic>(
      // init: controller,
      tag: '${Constant.matchFilterTagResult}${widget.pageIndex}',
      builder: (_) {
        return VisibilityDetector(
          key: const Key('end'),
          onVisibilityChanged: (VisibilityInfo info) {
            if (info.visibleBounds.isEmpty && logic.groupMatchList != null) {
              logic.getMatch();
            }
          },
          child: EasyRefresh.builder(
            controller: logic.refreshC,
            header: Styles.refreshHeader(position: IndicatorPosition.locator),
            onRefresh: () async {
              Utils.onEvent('bspd_sx');
              await logic.getMatch();
            },
            childBuilder: (BuildContext context, ScrollPhysics physics) =>
                CustomScrollView(
              physics: physics,
              slivers: [
                const HeaderLocator.sliver(),
                if (SpUtils.matchLqAds?[3].hasValue == false ||
                    DateTime.now()
                            .difference(DateTime.parse(SpUtils.matchLqAds![3]))
                            .inHours >
                        24)
                  SliverToBoxAdapter(
                    child: AdsLabel(
                      adsTag: "match_lq_赛果",
                      close: 3,
                      tapType: 'match_advertising',
                      tagParam: "赛果",
                      margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                      onClose: () => setState(() {}),
                    ),
                  ),
                LoadingWidget<int>(
                    data: logic.matchList.length,
                    isLoading: logic.firstLoad,
                    loading: const LoadingMatchList.sliver(sportsId: 2),
                    noData: NoDataWidget.sliver(
                      tip: logic.quickFilter == QuickFilter.yiji
                          ? '暂无一级比赛'
                          : (logic.quickFilter == QuickFilter.jingcai
                              ? '暂无竞篮比赛'
                              : '暂无比赛'),
                    ),
                    child: () => SliverList(
                        delegate: SliverChildBuilderDelegate(
                            childCount: logic.matchList.length,
                            (context, index) =>
                                LqMatchCell(logic.matchList[index])))),
                SliverToBoxAdapter(
                  child: Container(height: 80),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  didScroll() {
    Get.find<NavigationLogic>().onMatchPageScroll();
  }
}
